package com.polaris.live.ui.user.task

import android.os.Bundle
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.adapter.TaskCenterAnchorAdapter
import com.polaris.live.adapter.TaskCenterTodayAdapter
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.FragmentTaskCenterDialogBinding
import com.polaris.live.dialog.common.TipsDialog
import com.polaris.live.popup.PublicTipsPopup
import com.polaris.live.popup.TaskRewardPopup
import com.polaris.live.resp.back_resp.UserTaskListV2Resp
import com.polaris.live.translation.R
import com.polaris.live.utils.TaskPrizeAnimationProxy
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.utils.route.RouterUtils
import com.polaris.live.viewmodel.TaskCenterViewModel

/**
 * TaskCenterFragment
 * @author Created by 天晴 on 2024/10/28 13:54
 * @since 1.0.0
 **/
class TaskCenterDialogFragment : BaseVbFragment<TaskCenterViewModel, FragmentTaskCenterDialogBinding>() {

    private val mAdapter: TaskCenterTodayAdapter by lazy {
        TaskCenterTodayAdapter()
    }

    private val mAnchorAdapter: TaskCenterAnchorAdapter by lazy {
        TaskCenterAnchorAdapter()
    }
    private var dismissBack: (() -> Unit)? = null

    private val pox by lazy {
        TaskPrizeAnimationProxy(mBinding.flTask, this)
    }
    private var mUserTaskListV2Resp: UserTaskListV2Resp? = null
    private var canAgencyClaimedCount = 0 //未领数量主播
    private var canUserClaimedCount = 0 //未领数量用户

    private var showAgencyTasks = true //显示主播任务
    override fun initView(savedInstanceState: Bundle?) {
        mBinding.recycler.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
            adapter = mAnchorAdapter
            itemAnimator = null
        }
        mBinding.recyclerDay.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.VERTICAL, false)
            adapter = mAdapter
            itemAnimator = null
        }
        setClickClaim()
        mViewModel.getTask()
        initListener()
        initObserver()
    }

    private fun setClickClaim() {
        if (showAgencyTasks) {
            mBinding.oneClickClaimBtn.setBackgroundResource(com.polaris.live.R.drawable.shape_task_bg)
            mBinding.oneClickClaimBtn.setTextColor(ColorUtils.getColor(com.polaris.live.R.color.white))
        } else {
            mBinding.oneClickClaimBtn.setBackgroundResource(com.polaris.live.R.drawable.shape_task_bg_2)
            mBinding.oneClickClaimBtn.setTextColor(ColorUtils.getColor(com.polaris.live.common.R.color.color_202028))
        }
        setOneClaim()
    }

    private fun setOneClaim() {
        val str = if (showAgencyTasks) canAgencyClaimedCount else canUserClaimedCount
        mBinding.oneClickClaimTv.text =
            getColoredString(
                str.toString(),
                StringUtils.getString(R.string.not_been_claimed, str.toString())
            )
    }

    private fun getColoredString(memberPrice: String, baseString: String): SpannableString {
        val fullString = String.format(baseString, memberPrice)
        val spannableString = SpannableString(fullString)
        val startIndex = fullString.indexOf(memberPrice)
        val endIndex = startIndex + memberPrice.length
        val color = if (showAgencyTasks) {
            ContextCompat.getColor(requireContext(), com.polaris.live.R.color.color_893AFF)
        } else {
            ContextCompat.getColor(requireContext(), com.polaris.live.R.color.color_aaf000)
        }
        spannableString.setSpan(ForegroundColorSpan(color), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannableString
    }

    private fun initListener() {
        mAdapter.setItemListener({ explainType ->
            mUserTaskListV2Resp?.rewardExplains?.get(explainType.toString())?.let { explain ->
                TipsDialog.show(requireContext(), explain.title, explain.content)
            }
        }, { item ->
            when {
                item.rewards.any { it.status == 1L } -> { //可领取
                    val taskIds = item.rewards
                        .filter { it.status == 1L }
                        .map { it.taskId }
                    mViewModel.taskReceive(taskIds, true)
                }

                item.rewards.any { it.status == 0L } -> {  //进行中
                    dismissBack?.invoke()
                    item.rewards.firstOrNull { it.status == 0L }?.roomRouter?.let { router ->
                        RouterUtils.routerGoto(router)
                    }
                }
            }

        })
        mAnchorAdapter.setItemListener({ explainType ->
            mUserTaskListV2Resp?.rewardExplains?.get(explainType.toString())?.let { explain ->
                TipsDialog.show(requireContext(), explain.title, explain.content)
            }
        }, { item ->
            when {
                item.rewards.any { it.status == 1L } -> { //可领取
                    val taskIds = item.rewards
                        .filter { it.status == 1L }
                        .map { it.taskId }
                    mViewModel.taskReceive(taskIds)
                }

                item.rewards.any { it.status == 0L } -> {  //进行中
                    dismissBack?.invoke()
                    item.rewards.firstOrNull { it.status == 0L }?.roomRouter?.let { router ->
                        RouterUtils.routerGoto(router)
                    }
                }
            }
        })
        mBinding.oneClickClaimBtn.setOnSingleClickListener {
            if (showAgencyTasks) {
                mViewModel.taskReceive(null)
            } else {
                mViewModel.taskReceive(null, true)
            }
        }
        mBinding.todayRl.setOnClickListener {
            showAgencyTasks = false
            mBinding.recycler.visibility = View.GONE
            mBinding.dayRecyclerLl.visibility = View.VISIBLE
            mBinding.taskTitleRightImg.setImageResource(com.polaris.live.R.drawable.task_today_title_half)
            mBinding.taskTitleLeftImg.setImageResource(com.polaris.live.R.drawable.task_no_selected_left)
            setClickClaim()
        }
        mBinding.anchorRl.setOnClickListener {
            showAgencyTasks = true
            mBinding.recycler.visibility = View.VISIBLE
            mBinding.dayRecyclerLl.visibility = View.GONE
            mBinding.taskTitleRightImg.setImageResource(com.polaris.live.R.drawable.task_no_selected_right)
            mBinding.taskTitleLeftImg.setImageResource(com.polaris.live.R.drawable.task_today_achor_half)
            setClickClaim()
        }
        mBinding.activeView.setOnClickListener({ dailyTask, activeValue ->
            mViewModel.taskActiveReceive(activeValue, dailyTask)
        }) { explainType ->
            mUserTaskListV2Resp?.rewardExplains?.get(explainType.toString())?.let { explain ->
                TipsDialog.show(requireContext(), explain.title, explain.content)
            }
        }
    }

    private fun initObserver() {
        mViewModel.taskLiveData.observe(this) { resultState ->
            parseState(resultState, {
                initDataView(it)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
            mBinding.widgetLoading.visibility = View.GONE
        }
        mViewModel.taskReceiveData.observe(this) { resultState ->
            parseState(resultState, {
                mViewModel.getTask()
                if (it.taskIds == null) {
                    pox.setData(it.data.rewards)
                } else {
                    if (it.data.rewards.size > 6) {
                        pox.setData(it.data.rewards)
                    } else if (it.data.rewards.isNotEmpty()) {
                        TaskRewardPopup.showPop(requireContext(), mViewModel, it.data)
                    }

                }
            }, {
                if (it.errCode == 980006001) { // 没有绑定谷歌验证
                    PublicTipsPopup.show(
                        requireContext(), this,
                        StringUtils.getString(R.string.prompt),
                        StringUtils.getString(R.string.bind_your_google_account),
                        StringUtils.getString(R.string.go_bind),
                        StringUtils.getString(R.string.cancel),
                        isViewMode = false,
                        onTop = {
                            dismissBack?.invoke()
                            Router.instance.setPath(RoutePath.TASK_CENTER_ACTIVITY)
                                .apply {
                                    val taskIds = it.ext?.get("taskIds") as? List<Long>
                                    taskIds?.let { id ->
                                        this.withLongArray("taskId", id.toLongArray())
                                    }
                                    val receiveUserReward = it.ext?.get("receiveUserReward") as? Boolean
                                    receiveUserReward?.let { receive ->
                                        this.withBoolean("receiveUserReward", receive)
                                    }
                                    this.withBoolean("bind", true)
                                }
                                .navigation(requireActivity())
                        },
                        onBottom = {
                        }
                    )

                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }
            })
        }
        mViewModel.taskActiveReceiveData.observe(this) { resultState ->
            parseState(resultState, {
                mViewModel.getTask()
                if (it.data.rewards.size > 6) {
                    pox.setData(it.data.rewards)
                } else if (it.data.rewards.isNotEmpty()) {
                    TaskRewardPopup.showPop(requireContext(), mViewModel, it.data)
                }
            }, {
                if (it.errCode == 980006001) { // 没有绑定谷歌验证
                    PublicTipsPopup.show(
                        requireContext(), this,
                        StringUtils.getString(R.string.prompt),
                        StringUtils.getString(R.string.bind_your_google_account),
                        StringUtils.getString(R.string.go_bind),
                        StringUtils.getString(R.string.cancel),
                        onTop = {
                            dismissBack?.invoke()
                            Router.instance.setPath(RoutePath.TASK_CENTER_ACTIVITY)
                                .apply {
                                    val activeValue = it.ext?.get("activeValue") as? Long
                                    val dailyTask = it.ext?.get("dailyTask") as? Boolean
                                    this.withLong("activeValue", activeValue ?: -1)
                                    this.withBoolean("dailyTask", dailyTask ?: false)
                                    this.withBoolean("bind", true)
                                }
                                .navigation(requireActivity())
                        },
                        onBottom = {
                        }
                    )

                } else {
                    ToastGravity.showGravity(it.errorMsg)
                }

            })
        }
    }

    fun setDismissBack(dismissBack: () -> Unit) {
        this.dismissBack = dismissBack
    }

    private fun initDataView(data: UserTaskListV2Resp) {
        mUserTaskListV2Resp = data
        mBinding.loginView.setData(data.dailyTask)
        //没有个人每日任务
        if (data.dailyTask.tasks.isEmpty() && data.activeTask.tasks.isEmpty() && data.activeTask.weekTasks.isEmpty()) {
            mBinding.tasksUserRl.visibility = View.GONE
            if (data.agencyTasks.tasks.isEmpty()) { //没有工会任务
                mBinding.tasksNoUserRl.visibility = View.GONE
            } else {
                mBinding.tasksNoUserRl.visibility = View.VISIBLE
                mBinding.noUserBg.setBackgroundResource(com.polaris.live.R.drawable.task_title_2)
                mBinding.noUserTv.text = StringUtils.getString(R.string.anchor_task)
                if (showAgencyTasks) {
                    showAgencyTasks = true
                    mBinding.recycler.visibility = View.VISIBLE
                    mBinding.dayRecyclerLl.visibility = View.GONE
                }
                mAnchorAdapter.setList(data.agencyTasks.tasks)
            }
        } else {
            if (data.agencyTasks.tasks.isEmpty()) { //没有工会任务
                mBinding.tasksNoUserRl.visibility = View.VISIBLE
                mBinding.tasksUserRl.visibility = View.GONE
                mBinding.noUserBg.setImageResource(com.polaris.live.R.drawable.task_title_1)
                mBinding.noUserTv.text = StringUtils.getString(R.string.daily_tasks)
                showAgencyTasks = false

                mBinding.recycler.visibility = View.GONE
                mBinding.dayRecyclerLl.visibility = View.VISIBLE
            } else {
                mBinding.tasksUserRl.visibility = View.VISIBLE
                mBinding.tasksNoUserRl.visibility = View.GONE
                if (showAgencyTasks) {
                    showAgencyTasks = true
                    mBinding.recycler.visibility = View.VISIBLE
                    mBinding.dayRecyclerLl.visibility = View.GONE
                    mBinding.taskTitleRightImg.setImageResource(com.polaris.live.R.drawable.task_no_selected_right)
                    mBinding.taskTitleLeftImg.setImageResource(com.polaris.live.R.drawable.task_today_achor_half)
                } else {
                    mBinding.taskTitleRightImg.setImageResource(com.polaris.live.R.drawable.task_today_title_half)
                    mBinding.taskTitleLeftImg.setImageResource(com.polaris.live.R.drawable.task_no_selected_left)
                }
                mAnchorAdapter.setList(data.agencyTasks.tasks)
            }
            mBinding.activeView.setData(data.activeTask)
            mAdapter.setList(data.userTasks.tasks)
        }

        canAgencyClaimedCount = 0
        canUserClaimedCount = 0
        data.agencyTasks.tasks.forEach { task ->
            task.rewards.forEach { reward ->
                if (reward.status == 1L) {
                    canAgencyClaimedCount++
                }
            }
        }
        data.userTasks.tasks.forEach { task ->
            task.rewards.forEach { reward ->
                if (reward.status == 1L) {
                    canUserClaimedCount++
                }
            }
        }
        setClickClaim()
        mBinding.oneClickClaimRl.visibility = View.VISIBLE
    }

}